package logic

import (
	"context"
	"github.com/pkg/errors"
	"novel_srv/cache"
	"novel_srv/internal/svc"
	"novel_srv/models"
	"novel_srv/novel"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddNovelLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddNovelLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddNovelLogic {
	return &AddNovelLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddNovelLogic) AddNovel(in *novel.AddNovelRequest) (*novel.AddNovelResponse, error) {
	// todo: add your logic here and delete this line
	var err error

	if in.Title == "" || in.Authors == "" || in.Types == "" {
		logx.Error("小说信息不能为空")
		return nil, errors.New("小说信息不能为空")
	}

	novels := models.Novel{
		Image:   in.Image,
		Title:   in.Title,
		Authors: in.Authors,
		Types:   in.Types,
	}
	if err = novels.AddNovel(); err != nil {
		logx.Error("加入书架失败")
		return nil, errors.New("加入书架失败")
	}

	cache.Rdb.Set(l.ctx, "novel_"+in.Title, novels, time.Minute*5)

	return &novel.AddNovelResponse{
		Id: int64(novels.ID),
	}, nil
}
